<template>
  <div class="form-setting-panel">
    <!-- start 标题 -->
    <h3 class="form-setting-panel-title">{{field.displayName}}</h3>   
    <!-- end 标题 -->
    <p class="form-design-warning">{{$t('common.form.tip.systemTemplateTips')}}</p>

    <!-- start 校验 -->
    <div class="form-setting-group form-setting-item">
      <h4 class="form-item-title">{{$t('common.base.check')}}</h4>
      <div class="form-item-box">
        <!-- 必填 -->
        <form-required-setting :field="field" @input="update"></form-required-setting>
      </div>
    </div>
    <!-- end 校验 -->

    <!-- start 选项 -->
    <div class="form-setting-options">
      <p>{{$t('common.form.preview.qualityRuleField.des1')}}</p>

      <div class="type-btn-group">
        <el-radio-group v-model="field.setting.dataType" size="medium" @change="changeDateType">
          <el-radio-button :label="0">{{$t('common.form.preview.qualityRuleField.label1')}}</el-radio-button>
          <el-radio-button :label="1">{{$t('common.form.preview.qualityRuleField.label2')}}</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 自定义日期显示 S  -->
      <template v-if="field.setting.dataType == 0">
        <div class="form-select-setting-list">
          <draggable tag="div" class="list-group" :list="options" v-bind="{ animation:380 }" handle=".handle">
            <div v-for="(option, index) in options" :key="index" class="form-select-setting-option flex-x">
              <div class="flex-1">
                <button type="button" class="btn-text handle"> <i class="iconfont icon-tuozhuaipaixu"></i></button>
                <input type="text" :value="option.value" @input="updateOption($event, option)" :maxlength="optionMaxLength">
                <button type="button" class="btn-text form-select-setting-delete" @click="delOption(option, index)"><i class="iconfont icon-minus-fill"></i></button>
                <template v-if="!field.isMulti">
                  <button type="button" :class="['btn-text', 'form-select-setting-default',option.isDefault && 'btn-active']" @click="setDefaultOption(option)"> <i class="iconfont icon-check-fill"></i></button>
                  <span class="form-select-setting-defaultValue" v-if="option.isDefault">{{$t('common.base.default')}}</span>
                </template>
              </div>
              <base-select-language 
                :field="field"
                :defaultOption="{
                  formType:'text',
                }"
                :max="optionMaxLength"
                :defaultValue="option.value"
                :defaultValueLanguage="option.language || {}"
                defaultFormType="text"
                @save="data => saveOptionLanguage(data, option)"
              >
              </base-select-language>
            </div>
          </draggable> 
        </div>
        <div class="form-setting-group form-select-setting-operation form-select-setting-btnbox">
          <button type="button" class="btn-text" @click="addOption">{{$t('common.base.addOption')}}</button>
          <div class="btn-divider"></div>
          <button type="button" class="btn-text" @click="showBatchModal">{{$t('common.base.bulkEdit')}}</button>
        </div>
      </template>
      <!-- 自定义日期显示 E -->

      <!-- 关联产品日期 S -->
      <template v-if="field.setting.dataType == 1">
        <div>
          <p>{{$t('common.form.preview.qualityRuleField.des2')}}</p>
          <el-select 
            v-model="selectVal" 
            multiple
            clearable  
            collapse-tags
            :placeholder="$t('common.placeholder.select')"
            :style="{width: '100%'}"
            @change="changeSelectRelationProductDate">
            <el-option
              v-for="item in productOptions"
              :key="item.fieldName"
              :label="item.displayName"
              :value="item.fieldName">
            </el-option>
          </el-select>
        </div>

      </template>
      <!-- 关联产品日期 S -->

      <div style="margin-top: 20px;">
        <p>{{ $t('component.formQualityRuleSetting.configTitle1') }}</p>
        <formulaShow
          v-if="productFieldsInit"
          class="form-formula-setting-result"
          :prop-formula="formula"
          :calculationFields="calculationFields"
          @click.native="openFormulaSetDialog">
        </formulaShow>
      </div>
    </div>
    <!-- end 选项 -->
   
    <!-- start 批量编辑选项 -->
    <base-modal 
      :title="$t('common.base.batchEditOptions')"
      width="520px"
      class="form-select-setting-modal"
      :show.sync="batchModalShow"
      :mask-closeable="false">
      <div class="form-select-setting-batch">
        <textarea :value="optionText" @input="updateOptionText" rows="10"></textarea>
        <div class="form-select-setting-warn" v-if="errMessage">{{errMessage}}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <span class="form-select-tips">{{$t('common.base.everyLinePointToOneOption')}}</span>
        <el-button @click="batchModalShow = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="batchEdit">{{$t('common.base.save')}}</el-button>
      </div>
    </base-modal>
    <!-- end 批量编辑选项 -->

    <!-- 计算公式 -->
    <BaseCalculationFormulaSpectial
      ref="BaseCalculationFormula"
      :calculation-fields="calculationFields"
      :fields="fields"
      :formulaFuncFilter="['ADD', 'MAX', 'MIN']"
      @confirm="saveFormula"
      source="productQualityRule"
    />
  </div>
</template>

<script>
import { SELECT_OPTION_LENGTH_MAX } from '../../config'
import { getProductFields } from '@src/api/ProductApi'

import _ from 'lodash';
import draggable from 'vuedraggable';
import SettingMixin from '@src/component/form/mixin/setting';
import FormSelectMixin from '@src/component/form/mixin/form.select';
import { settingProps } from '@src/component/form/components/props';
import Platform from '@src/platform';
import BaseCalculationFormulaSpectial from '@src/component/common/BaseCalculationFormulaSpectial'
import { getSameField, getSameLevelFields } from '@src/mform/util';
import { defaultCalculationFields } from './utils/formula';
import formulaShow from './components/formulaShow'
const SUPPORT_FORM_TYPE = ['number', 'date', 'datetime'];
import { DefaultLang, defaultCNKey } from '@src/util/languages.js'
import locales from '@src/locales'

export default {
  name: 'form-quality-rule-setting',
  mixins: [SettingMixin, FormSelectMixin],
  props: {
    ...settingProps,
    /** 用于获取FormDesign实例 */
    getContext: Function
  },
  computed: {
    optionMaxLength(){
      return SELECT_OPTION_LENGTH_MAX
    },
    defaultValueConfig() {
      return this.field.setting.defaultValueConfig || {};
    },
    /* 计算公式 */
    formula() {
      let formula = this.field.setting?.formula || [];

      // 判断计算公式的运算对象是否已删除或已隐藏，增加标识
      formula.map(item => {
        let field = getSameField(this.calculationFields, item.fieldName);
        item.isDelete = item.fieldName && (!field || !!field.isHidden);
      });
      return formula;
    },
    /* 支持运算的字段列表 */
    calculationFields() {
      // 如果不走保存能计算公式能实时显示对应number 的类型的form走 this.$parent.value 走保存的直接走this.fields
      // const previewFields = this.$parent.value;
      let fields = getSameLevelFields(this.field, this.fieldsForCalculationFields)
      const currentField = this.field;

      // const mergeFields = this.mergeSubform(fields);
      return fields.filter(field => {
        // let isSelect = field.formType == 'select' && !field.setting?.isMulti;
        // 不支持下拉菜单(因为预览的没有id) 走预览的组件列表的话
        // return (field.formType === 'number') && !field.isHidden;
        // 不走预览的列表（要保存才能显示对应的number类型的组件）
        return (SUPPORT_FORM_TYPE.includes(field.formType) && field.fieldName !== currentField.fieldName) && (field.id || field.fixedCalculation) && !field.isHidden;
      });
    },
    fieldsForCalculationFields() {
      return [...this.defaultCalculationFields, ...this.fields, ...this.productFields]
    }
  },
  data(){
    return {
      index: this.field.options.length,
      batchModalShow: false, 
      optionText: '', // 批量编辑文本
      errMessage: null,
      productOptions: [], // 关联产品日期下拉框
      selectVal: [],
      productFields: [],
      productFieldsInit: false,
      defaultCalculationFields: defaultCalculationFields()
    }
  },
  mounted() {
    this.getRelationProductList()
  },
  methods: {
    // 获取关联产品下拉框数据
    async getRelationProductList() {
      this.productFieldsInit = false
      if (this.field.setting.dataType === 1) {
        this.selectVal = [];
      }
      try { 
        let res = await getProductFields({isFromSetting: false});
        this.productFieldsInit = true
        if (res.data.length == 0) return

        this.productFields = res.data || []

        if (this.field.setting.dataType !== 1) return

        this.productOptions = res.data.filter(item => {
          return item.formType == 'date'
        })

        let arr = this.field.setting.fieldNames

        this.productOptions.forEach(item => {
          if (arr.includes(item.fieldName)) {
            this.selectVal.push(item.fieldName) 
          }
        });
      } catch (error) {
        console.error('customer-product-table fetch product fields error',error);
      }
    },
    changeDateType(val) {
      this.getRelationProductList()
    },
    // change关联产品日期
    changeSelectRelationProductDate(newValue) {
      this.field.setting.fieldNames = newValue;
    },
    updateDependencies(val){
      this.$emit('input', {prop: 'dependencies', value: val, operate: 'update'})
    },
    updateOption(event, option){
      option.value = event.target.value;
      option.language[locales.locale] = event.target.value
      this.$emit('input', {value: this.field, prop: 'dependencies', operate: 'delete'})
    },
    delOption(option, index){
      if(this.options.length <= 1) return alert(this.$t('common.base.tip.evenHaveOneOption2'))

      // 如果是删除默认值，清空默认值
      if(option.isDefault) this.$emit('input', {value: null, prop: 'defaultValue'});

      let options = _.cloneDeep(this.options);
      options.splice(index, 1);

      this.$emit('input', {value: options, prop: 'options'})
      this.$emit('input', {value: this.field, prop: 'dependencies', operate: 'delete'})
    },
    saveOptionLanguage(data, option){
      if(option.language){
        option.language = {...DefaultLang(), ...option.language}
      }
      
      for (let i in data) {
        this.$set(option.language, i, data[i])
      }
      option.value = option.language[this.$i18n.locale]
    },
    batchEdit(){
      let newValues = this.optionText.split('\n').filter(option => option);
      if(!newValues.length) {
        Platform.alert(this.$t('common.base.tip.evenHaveOneOption2'));
        return false;
      }

      this.errMessage = this.validateOptions(newValues);
      if(this.errMessage) return false;
      let oldOptions = this.options;
      let defaultValue = null;
      let newOptions = []
      newValues.forEach((item, index)=>{
        // 此对象需与options对应
        let items = {
          isDefault:false,
          language:{},
          value:''
        };
        if(oldOptions[index]){
          try{
            items = {...items, ...oldOptions[index]}
          }catch(err){
            console.warn(err, 'newValues.forEach is Error', index)
          }
        }
        if(!this.field.isMulti && defaultValue === null){
          defaultValue = items.isDefault ? items.language?.[defaultCNKey] || items.value : null
        }
        // TODO 如果当前值为空是否需要替换
        items['value'] = item || items.value || '';
        if(items.language){
          items.language[this.$i18n.locale] = item || '';
        }else{
          items['language'] = {
            [this.$i18n.locale] : item || ''
          }
        }
        // 沿用主语言作为每个选项的标识
        let itemDefaultValue = items.language?.[defaultCNKey] || item
        items['isDefault'] = itemDefaultValue === defaultValue ? true : false ;
        newOptions.push(items)
      })
      this.$emit('input', {value: newOptions, prop: 'options'})
      this.$emit('input', {value: this.field, prop: 'dependencies', operate: 'delete'})

      this.batchModalShow = false;
    },
    openFormulaSetDialog() {
      this.$refs.BaseCalculationFormula.open(this.formula);
    },
    saveFormula(formula) {
      // const includeAmountList = [];
      const formulaStr = formula.map(item => {
        if(item.fieldName) {
          // 金额也暂时不加~
          // 是否存在金额字段
          // const nameArr = item.fieldName.split('_');
          // includeAmountList.push(INCLUDE_PRICE.includes(nameArr[1]))

          if(item.parentFieldId) return `${item.parentFieldId}.${item.fieldName}`;
          return item.fieldName;
        }
        return item.value;
      }).join('');

      // const includeAmount = internationalGray && includeAmountList.some(x => x);
      // this.updateBatch({formulaStr, formula, includeAmount});
      this.updateBatch({formulaStr, formula});
    },
    updateBatch(value) {
      this.$emit('input', { prop: 'assign', setting: {...this.defaultValueConfig, ...value}});
    },
    // mergeSubform (fields) {
      // let allSubFormList = [];
      // fields.forEach(field =>{
      //   if(isSubForm(field)) {
      //     allSubFormList = [...allSubFormList, ...field.subFormFieldList];
      //   }
      // });
      // return fields.concat(allSubFormList);
      // return [...fields];
    // }
  },
  components: {
    draggable,
    BaseCalculationFormulaSpectial,
    formulaShow
  }
}
</script>
<style lang="scss">
.type-btn-group {
  margin-bottom: 20px;
  .el-radio-group {
   width: 100%;
    label {
      width: 50%;
      margin: 0 !important; 
      .el-radio-button__inner {
        width: 100%;
        padding: 8px 20px;
      } 
    }
  }
}
</style>
